<template>
  <div class="todoapp">
    <TodoHeader @addTaskEvent="addTaskFn" :arr="showArr"></TodoHeader>
    <TodoMain :arr="showArr" @delEvent="delFn"></TodoMain>
    <TodoFooter
      :arr="showArr"
      @changeEvent="changeFn"
      @clearEvent="clearFn"
    ></TodoFooter>
  </div>
</template>

<script>
//样式引入
import "./styles/base.css";
import "./styles/index.css";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem("74-todolist")) || [],
      curType: "all",
    };
  },
  methods: {
    addTaskFn(name) {
      if (!name) {
        return alert("任务名不能为空！");
      }
      let id =
        this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 100;
      this.list.push({
        id: id,
        name: name,
        isDone: false,
      });
    },
    //删除
    delFn(id) {
      //根据ID获取对应数组中的索引值
      //findIndex:这个方法用来查找并返回下标值，当符合条件判断的时候，这个方法就会立刻返回下标值
      let index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeFn(type) {
      this.curType = type;
    },
    clearFn() {
      this.list = this.list.filter((item) => {
        return item.isDone === false;
      });
    },
  },
  computed: {
    showArr() {
      if (this.curType === "yes") {
        let newArr = this.list.filter((item) => {
          return item.isDone === true;
        });
        return newArr;
      } else if (this.curType === "no") {
        return this.list.filter((item) => {
          return item.isDone === false;
        });
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(arr) {
        //数据发生变化进行实时缓存
        localStorage.setItem("74-todolist", JSON.stringify(arr));
      },
    },
  },
};
</script>

<style>
</style>